#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>

void Usage(std::string proc)
{
    std::cerr << "Usage \n\t" << proc << " svr_ip svr_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string svr_ip = argv[1];
    std::string svr_port = argv[2];
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock create error!" << std::endl;
        return 2;
    }
    sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, len);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    server.sin_port = htons(atoi(svr_port.c_str()));

    if (connect(sock, (sockaddr *)&server, len) < 0)
    {
        std::cerr << "connect faild!" << std::endl;
        return 3;
    }
    std::cout << "connect successfully!" << std::endl;
    while (true)
    {
        std::cout << "please input:";
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        fgets(buffer, sizeof(buffer) - 1, stdin);
        write(sock, buffer, strlen(buffer));
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "server echo#" << buffer << std::endl;
        }
    }

    return 0;
}